package com.xdy.music;

import com.xdy.music.bean.LastPlayInfo;
import com.xdy.music.bean.PlayBean;
import com.xdy.music.bean.SoundBean;
import com.xdy.music.common.Constants;
import com.xdy.music.stage.AddGroupStage;
import com.xdy.music.util.ImageUtils;
import com.xdy.music.util.XMLUtils;
import javafx.animation.KeyFrame;
import javafx.animation.KeyValue;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.embed.swing.SwingFXUtils;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Cursor;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.control.Label;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.effect.GaussianBlur;
import javafx.scene.image.*;
import javafx.scene.image.Image;
import javafx.scene.layout.*;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.scene.paint.Color;
import javafx.scene.paint.CycleMethod;
import javafx.scene.paint.LinearGradient;
import javafx.scene.paint.Stop;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Rectangle;
import javafx.scene.text.Font;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import javafx.util.Duration;
import org.jaudiotagger.audio.exceptions.InvalidAudioFrameException;
import org.jaudiotagger.audio.exceptions.ReadOnlyFileException;
import org.jaudiotagger.audio.mp3.MP3AudioHeader;
import org.jaudiotagger.audio.mp3.MP3File;
import org.jaudiotagger.tag.TagException;
import org.jaudiotagger.tag.id3.*;
import org.jaudiotagger.tag.id3.framebody.FrameBodyAPIC;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.math.BigDecimal;
import java.net.URI;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 主舞台
 */
public class MainApp extends Application {

    private Stage primaryStage;//全局舞台对象

    private double mouseX;//鼠标横坐标
    private double mouseY;//鼠标纵坐标

    private double offsetX;//鼠标屏幕横坐标
    private double offsetY;//鼠标屏幕纵坐标

    private VBox groupVBox;//显示歌单容器
    private HBox groupHBox;//单个歌单

    private Label groupNameLabel;//当前歌单名称标签

    private TableView<PlayBean> tableView;//播放列表表格
    private int currentIndex;//当前播放歌曲的索引
    private int preSecond;//当前播放的时间的前一秒--设置滚动条
    private PlayBean currentPlayBean;//当前播放的PlayBean
    private Label totalTimeLabel;//总时长标签
    private ImageView currentImageView;//碟片
    private Timeline timeline;//碟片旋转动画
    private ImageView backImageView;//背景图片
    private ImageView playBtnImage;//播放按钮图片
    private Label playLabel;//播放按钮标签
    private Slider sliderSong;//播放滚动条
    private Label playTimeLabel;//已播放时间标签
    private Slider volumeSlider;//音量进度条
    private ProgressBar volumeProgress;//音量进度条
    private int playMode = 1;//播放模式1：循环播放 2：随机播放 3：单曲循环
    private VBox lrcVBox;//歌词Vbox
    private ArrayList<BigDecimal> lrcList = new ArrayList<>();//存储歌词时间
    private int currentLrcIndex;//当前播放的歌词索引
    private double preVolume;//静音之前的音量
    private ScrollPane scrollPane;//歌词滚动面板

    private TableColumn c2;//歌曲标题列头
    private TableColumn c3;//歌手列头
    private TableColumn c4;//专辑列头
    private TableColumn c5;//大小列头
    private TableColumn c6;//时间列头

    private List<SoundBean> soundBeans;//当前正在播放的歌单项

    private static final ExecutorService EXECUTOR_SERVICE = Executors.newFixedThreadPool(3);

    /**
     * 舞台初始化
     * @param primaryStage
     * @throws Exception
     */
    @Override
    public void start(Stage primaryStage) throws Exception {
        this.primaryStage = primaryStage;
        BorderPane borderPane = new BorderPane();//创建布局管理器
        borderPane.setBackground(new Background(new BackgroundFill(Color.rgb(47, 47, 47), null, null)));
        borderPane.setTop(getTopPanel());//设置顶部面板
        borderPane.setLeft(getLeftPanel());//设置左侧面板
        borderPane.setBottom(getBottomPanel());//设置底部面板
        borderPane.setCenter(getCenterPanel());//设置中间面板
        Scene scene = new Scene(borderPane, Constants.STAGE_WIDTH, Constants.STAGE_HEIGHT);//创建场景
        scene.setCursor(Cursor.HAND);
        primaryStage.setScene(scene);//设置场景
        primaryStage.initStyle(StageStyle.UNDECORATED);//没有任何装饰
        primaryStage.getIcons().add(new Image("image/upload/icon.jpeg"));
        primaryStage.widthProperty().addListener(new ChangeListener<Number>() {
            @Override
            public void changed(ObservableValue<? extends Number> observable, Number oldValue, Number newValue) {
                double diffValue = newValue.doubleValue() - oldValue.doubleValue();
                if (!Double.isNaN(diffValue)){
                    lrcVBox.setLayoutX(lrcVBox.getLayoutX() + diffValue / 2);
                    scrollPane.setPrefWidth(scrollPane.getPrefWidth() + diffValue);
                    c2.setPrefWidth(c2.getPrefWidth() + diffValue / 6);
                    c3.setPrefWidth(c3.getPrefWidth() + diffValue / 6);
                    c4.setPrefWidth(c4.getPrefWidth() + diffValue / 6);
                    c5.setPrefWidth(c5.getPrefWidth() + diffValue / 6);
                    c6.setPrefWidth(c6.getPrefWidth() + diffValue / 6);
                }
            }
        });
        //读取上次播放的歌单和歌曲信息
        LastPlayInfo playInfo = XMLUtils.getPrePlayInfo();
        if (playInfo != null){
            this.groupNameLabel.setText(playInfo.getGroupName());
            if (playInfo.getIndex() != 0){
                this.currentIndex = playInfo.getIndex();
            }
            readAllSoundByGroup();
            this.tableView.getSelectionModel().select(currentIndex);
        }
        primaryStage.show();//展示窗口
    }

    /**
     * 获取中间面板
     * @return
     */
    private Node getCenterPanel() {
        //读取上次关闭时保存的歌单和索引信息
        String[] playInfo = XMLUtils.readPrePlayInfo();
        //歌单标签
        Label label = new Label("歌单：");
        label.setTextFill(Color.rgb(180,0,0));
        BorderStroke borderStroke = new BorderStroke(
                Color.rgb(180,0,0),
                Color.rgb(180,0,0),
                Color.rgb(180,0,0),
                Color.rgb(180,0,0),
                BorderStrokeStyle.SOLID,
                BorderStrokeStyle.SOLID,
                BorderStrokeStyle.SOLID,
                BorderStrokeStyle.SOLID,
                new CornerRadii(1),
                new BorderWidths(1),
                new Insets(1,2,1,2)
        );
        label.setBorder(new Border(borderStroke));
        label.setLayoutX(30);
        label.setLayoutY(10);
        label.setPrefWidth(55);
        label.setPrefHeight(25);
        label.setAlignment(Pos.CENTER);
        //歌单名称标签
        groupNameLabel = new Label(playInfo == null ? "暂无记录" : playInfo[0]);
        groupNameLabel.setLayoutX(100);
        groupNameLabel.setLayoutY(9);
        groupNameLabel.setPrefWidth(200);
        groupNameLabel.setPrefHeight(25);
        groupNameLabel.setTextFill(Color.BLUE);
        groupNameLabel.setFont(new Font("黑体",18));
        groupNameLabel.setAlignment(Pos.CENTER_LEFT);
        //碟片的图片
        currentImageView = new ImageView("image/upload/yuanpan.jpg");
        currentImageView.setFitWidth(200);
        currentImageView.setFitHeight(200);
        Label label2 = new Label("",currentImageView);
        label2.setLayoutX(30);
        label2.setLayoutY(60);
        //定义一个圆
        Circle circle = new Circle();
        circle.setCenterX(100);//圆心横坐标
        circle.setCenterY(100);//圆心纵坐标
        circle.setRadius(85);//圆的半径
        currentImageView.setClip(circle);//设置图片剪切
        //定义时间轴动画
        timeline = new Timeline();
        timeline.getKeyFrames().addAll(
                new KeyFrame(new Duration(0),new KeyValue(currentImageView.rotateProperty(),0)),//起始帧
                new KeyFrame(new Duration(5 * 1000),new KeyValue(currentImageView.rotateProperty(),360))//结束帧
        );
        timeline.setCycleCount(Timeline.INDEFINITE);//无线循环播放动画
        //运行动画
//        timeline.play();
        //歌词VBox容器
        lrcVBox = new VBox(15);
        lrcVBox.setPadding(new Insets(20,20,20,20));
        lrcVBox.setLayoutX(250);
        lrcVBox.setLayoutY(0);
        //歌单列表标签
        Label label3 = new Label("歌单列表");
        label3.setPrefWidth(80);
        label3.setPrefHeight(25);
        label3.setTextFill(Color.WHITE);
        label3.setAlignment(Pos.CENTER);
        label3.setBackground(new Background(new BackgroundFill(Color.rgb(180,0,0),null,null)));
        label3.setLayoutX(30);
        label3.setLayoutY(270);
        //歌词背景图片
        Image image = new Image("image/upload/bg.png");
        //获取图片像素读取器
        PixelReader pixelReader = image.getPixelReader();
        //创建一个图片输入流WritableImage
        WritableImage wImage = new WritableImage(
                (int)image.getWidth(),
                (int)image.getHeight()
        );
        //创建一个像素写入器
        PixelWriter pixelWriter = wImage.getPixelWriter();
        //循环读取image中的每个像素
        for (int i = 0; i < image.getWidth(); i++) {
            for (int j = 0; j < image.getHeight(); j++) {
                Color color = pixelReader.getColor(i, j);
                for (int k = 0; k < 4; k++) {
                    color.darker();//将当前颜色淡化4次
                }
                pixelWriter.setColor(i,j,color);//重新设置颜色
            }
        }
        backImageView = new ImageView(wImage);
        backImageView.setLayoutX(0);
        backImageView.setLayoutY(0);
        backImageView.setFitWidth(300);
        backImageView.setFitHeight(300);
        //高斯模糊
        GaussianBlur gaussianBlur = new GaussianBlur();
        gaussianBlur.setRadius(10);//模糊半径
        //背景图片设置高斯模糊
        backImageView.setEffect(gaussianBlur);
        //歌单列表下面的分割线
        Label labelLine = new Label();
        labelLine.setMinHeight(0);
        labelLine.setMinWidth(0);
        labelLine.setPrefHeight(20);
        labelLine.setPrefWidth(200);
        labelLine.setBackground(new Background(new BackgroundFill(Color.rgb(180,0,0),null,null)));
        labelLine.setLayoutX(0);
        labelLine.setLayoutY(label3.getLayoutY() + label3.getPrefHeight());
        //下侧歌单列表
        tableView = new TableView();
        tableView.setPrefWidth(960);

        tableView.getStylesheets().add("css/playTable.css");
        //列头
        TableColumn c1 = new TableColumn("序号");
        c1.setPrefWidth(80);
        c1.setCellValueFactory(new PropertyValueFactory<>("id"));
        c2 = new TableColumn("歌曲名称");
        c2.setPrefWidth(300);
        c2.setCellValueFactory(new PropertyValueFactory<>("soundName"));
        c3 = new TableColumn("歌手");
        c3.setPrefWidth(150);
        c3.setCellValueFactory(new PropertyValueFactory<>("artist"));
        c4 = new TableColumn("专辑");
        c4.setPrefWidth(100);
        c4.setCellValueFactory(new PropertyValueFactory<>("album"));
        c5 = new TableColumn("大小");
        c5.setPrefWidth(100);
        c5.setCellValueFactory(new PropertyValueFactory<>("length"));
        c6 = new TableColumn("时间");
        c6.setPrefWidth(100);
        c6.setCellValueFactory(new PropertyValueFactory<>("time"));
        TableColumn c7 = new TableColumn("操作");
        c7.setMinWidth(140);
        c7.setPrefWidth(140);
        c7.setCellValueFactory(new PropertyValueFactory<>("label"));
        tableView.getColumns().addAll(c1,c2,c3,c4,c5,c6,c7);
        tableView.setRowFactory(tv -> {
            TableRow<PlayBean> row = new TableRow<>();
            row.setOnMouseClicked(event -> {
                //验证双击
                if (event.getClickCount() == 2 && !row.isEmpty()){
                    //获取选中行的索引
                    this.currentIndex = row.getIndex();
                    //将前一秒设置为0
                    this.preSecond = 0;
                    //判断当前是否正在播放，如果是：将其停止
                    if (this.currentPlayBean != null){
                        this.currentPlayBean.getMediaPlayer().stop();
                    }
                    //获取当前的playBean
                    this.currentPlayBean = row.getItem();
                    //播放
                    play();
                }
            });
            return row;
        });
        //AnchorPane可以指定组件摆放位置
        AnchorPane anchorPane = new AnchorPane();
        anchorPane.setBackground(new Background(new BackgroundFill(Color.rgb(40,40,40),null,null)));
        anchorPane.getChildren().addAll(backImageView,label,groupNameLabel,label2,lrcVBox,label3,labelLine);
        //ScrollPane可以滚动
        scrollPane = new ScrollPane();
        scrollPane.setContent(anchorPane);
        scrollPane.setPrefWidth(1000);
        scrollPane.setPrefHeight(300);
        scrollPane.setVbarPolicy(ScrollPane.ScrollBarPolicy.NEVER);
        scrollPane.setHbarPolicy(ScrollPane.ScrollBarPolicy.NEVER);
        scrollPane.setPadding(new Insets(0,0,0,0));
        //设置ScrollPane禁止鼠标事件
        scrollPane.setMouseTransparent(true);
        anchorPane.prefWidthProperty().bind(scrollPane.prefWidthProperty());
        anchorPane.prefHeightProperty().bind(scrollPane.prefHeightProperty());
        backImageView.fitWidthProperty().bind(scrollPane.prefWidthProperty());
        backImageView.fitHeightProperty().bind(scrollPane.prefHeightProperty());
        lrcVBox.prefWidthProperty().bind(scrollPane.prefWidthProperty());
        lrcVBox.prefHeightProperty().bind(scrollPane.prefHeightProperty());
        labelLine.prefWidthProperty().bind(scrollPane.prefWidthProperty());
        c7.prefWidthProperty().bind(tableView.prefWidthProperty());
        //总Pane
        BorderPane centerPane = new BorderPane();
        centerPane.setTop(scrollPane);
        centerPane.setCenter(tableView);
        return centerPane;
    }

    /**
     * 播放的方法
     */
    private void play() {
        //加载歌词
        loadLrc();
        //选中当前行
        this.tableView.getSelectionModel().select(this.currentIndex);
        //设置总时间
        this.totalTimeLabel.setText(this.currentPlayBean.getTime());
        //设滚动条的总值
        this.sliderSong.setMax(this.currentPlayBean.getTotalSeconds());
        this.sliderSong.setMajorTickUnit(1);//每次前进1格
        this.sliderSong.setValue(0);
        this.preSecond = 0;
        //设置初始音量
        this.currentPlayBean.getMediaPlayer().setVolume(this.volumeProgress.getProgress());
        //开启播放音乐线程
        EXECUTOR_SERVICE.execute(new Runnable() {
            @Override
            public void run() {
                currentPlayBean.getMediaPlayer().play();
            }
        });
        //设置碟片
        if (this.currentPlayBean.getImage() != null){
            this.currentImageView.setImage(this.currentPlayBean.getImage());
        }else{
            this.currentImageView.setImage(new Image("image/upload/yuanpan.jpg"));
        }
        //设置旋转
        this.timeline.stop();
        this.timeline.play();
        //设置背景
        WritableImage wImage = this.currentPlayBean.getImage();
        if (wImage != null){
            //虚化
            WritableImage writableImage = new WritableImage((int) wImage.getWidth(), (int) wImage.getHeight());
            PixelReader pr = wImage.getPixelReader();
            PixelWriter pw = writableImage.getPixelWriter();
            for (int i = 0; i < wImage.getWidth(); i++) {
                for (int j = 0; j < wImage.getHeight(); j++) {
                    Color color = pr.getColor(i,j);
                    for (int k = 0; k < 4; k++) {
                        //四次淡化
                        color = color.darker();
                    }
                    //输出
                    pw.setColor(i,j,color);
                }
            }
            this.backImageView.setImage(writableImage);
        }else{
            Image image = new Image("image/upload/bg.png");
            //获取图片像素读取器
            PixelReader pixelReader = image.getPixelReader();
            //创建一个图片输入流WritableImage
            WritableImage writableImage = new WritableImage(
                    (int)image.getWidth(),
                    (int)image.getHeight()
            );
            //创建一个像素写入器
            PixelWriter pixelWriter = writableImage.getPixelWriter();
            //循环读取image中的每个像素
            for (int i = 0; i < image.getWidth(); i++) {
                for (int j = 0; j < image.getHeight(); j++) {
                    Color color = pixelReader.getColor(i, j);
                    for (int k = 0; k < 4; k++) {
                        color.darker();//将当前颜色淡化4次
                    }
                    pixelWriter.setColor(i,j,color);//重新设置颜色
                }
            }
            this.backImageView.setImage(writableImage);
        }
        //设置按钮为暂停按钮
        this.playBtnImage.setImage(new Image("image/icon/pause.png"));
        this.playLabel.setOnMouseEntered(event -> this.playBtnImage.setImage(new Image("image/icon/pause-dark.png")));
        this.playLabel.setOnMouseExited(event -> this.playBtnImage.setImage(new Image("image/icon/pause.png")));
    }

    /**
     * 加载lrc文件（歌词文件）
     */
    private void loadLrc() {
        if (this.currentPlayBean == null){
            return;
        }
        //初始化歌词VBox
        this.lrcVBox.getChildren().clear();
        this.lrcVBox.setLayoutY(50 * 2 - 10);//设置初始纵坐标在中间，保持上方留下两行歌词的空间
        this.lrcList.clear();
        this.currentLrcIndex = 0;
        //读取MP3文件
        File file = new File(this.currentPlayBean.getFilePath());
        //查找歌词文件
        File lrcFile = new File(file.getParent(),file.getName().substring(0,file.getName().lastIndexOf(".")) + ".lrc");
        if (!lrcFile.exists()){
            return;
        }
        //读取一行，封装歌词Label
        try {
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(lrcFile),"utf-8"));
            String row = null;
            while ((row = bufferedReader.readLine()) != null){
                if (row.indexOf("[") == -1 || row.indexOf("]") == -1){
                    //没有这两个符号，说明不是时间
                    continue;
                }
                if (row.charAt(1) < '0' || row.charAt(1) > '9'){
                    //如果一行中第一个字符不是数字说明也不是歌词
                    continue;
                }
                String strTime = row.substring(1,row.indexOf("]"));//结果示例：00:42.57
                String strMinute = strTime.substring(0,strTime.indexOf(":"));//取出分钟
                String strSecond = strTime.substring(strTime.indexOf(":") + 1);//取出秒数和毫秒
                //整数类型分钟
                int intMinute = Integer.parseInt(strMinute);
                //小数秒数
                BigDecimal secondBigDecimal = new BigDecimal(strSecond);
                //获取总的毫秒数
                BigDecimal totalSecond = new BigDecimal(intMinute * 60).add(secondBigDecimal).multiply(new BigDecimal(1000));
                this.lrcList.add(totalSecond);
                //获取歌词，封装Label
                String lrcStr = row.trim().substring(row.indexOf("]") + 1);
                Label lrcLabel = new Label(lrcStr);
                lrcLabel.setMinWidth(550);
                lrcLabel.setMinHeight(35);
                lrcLabel.setMaxHeight(35);

                lrcLabel.setPrefHeight(550);
                lrcLabel.setPrefHeight(35);
                lrcLabel.setTextFill(Color.rgb(53,53,53));
                lrcLabel.setFont(new Font("黑体",18));
                //居中显示
                lrcLabel.setAlignment(Pos.CENTER);
                //判断是否是第一行歌词
                if (this.lrcVBox.getChildren().size() == 0){
                    lrcLabel.setTextFill(Color.YELLOW);//把第一行设置成黄色
                    lrcLabel.setFont(new Font("黑体",30));//文字变大
                }
                //判断是否是第二行
                if (this.lrcVBox.getChildren().size() == 1){
                    lrcLabel.setTextFill(Color.WHITE);//把颜色改为白色
                }
                //把歌词添加到歌词容器中显示
                this.lrcVBox.getChildren().add(lrcLabel);
            }
            //最后添加广告
            if (this.currentPlayBean.getMediaPlayer().getTotalDuration().toMillis() - this.lrcList.get(this.lrcList.size() - 1).doubleValue() > 0){
                //如果歌曲的总的播放时间减去最后一个歌词显示的时间还大于0的话，就显示广告
                Label label = new Label("作者Email：2280944114@qq.com");
                label.setMinWidth(550);
                label.setMinHeight(35);
                label.setMaxHeight(35);
                label.setPrefHeight(550);
                label.setPrefHeight(35);
                label.setTextFill(Color.rgb(255,255,255));
                label.setFont(new Font("黑体",26));
                label.setAlignment(Pos.CENTER);
                this.lrcVBox.getChildren().add(label);
                this.lrcList.add(new BigDecimal(this.currentPlayBean.getMediaPlayer().getTotalDuration().toMillis()));

            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取底部面板
     * @return
     */
    private Node getBottomPanel() {
        //上一曲按钮
        ImageView iv1 = new ImageView("image/icon/pre.png");
        iv1.setFitHeight(45);
        iv1.setFitWidth(45);
        Label label1 = new Label("",iv1);
        label1.setOnMouseEntered(event -> iv1.setImage(new Image("image/icon/pre-dark.png")));
        label1.setOnMouseExited(event -> iv1.setImage(new Image("image/icon/pre.png")));
        label1.setOnMouseClicked(event -> {
            //停止当前播放
            if (this.currentPlayBean != null){
                this.currentPlayBean.getMediaPlayer().stop();
            }
            switch (this.playMode){
                case 1://循环播放
                    this.currentIndex--;//播放上一曲
                    if (this.currentIndex < 0){
                        this.currentIndex = tableView.getItems().size() - 1;//小于0设置到最后一个
                    }
                    this.currentPlayBean = tableView.getItems().get(this.currentIndex);
                    break;
                case 2://随机播放
                    Random random = new Random();
                    this.currentIndex = random.nextInt(tableView.getItems().size());//随机获取表格总数内的索引
                    this.currentPlayBean = tableView.getItems().get(this.currentIndex);
                    break;
                case 3://单曲循环
                    this.currentPlayBean.getMediaPlayer().seek(new Duration(0));//设置当前播放时间为0
                    break;
            }
            //播放
            play();
        });
        //播放按钮
        playBtnImage = new ImageView("image/icon/play.png");
        playBtnImage.setFitHeight(45);
        playBtnImage.setFitWidth(45);
        playLabel = new Label("",playBtnImage);
        playLabel.setOnMouseEntered(event -> playBtnImage.setImage(new Image("image/icon/play-dark.png")));
        playLabel.setOnMouseExited(event -> playBtnImage.setImage(new Image("image/icon/play.png")));
        playLabel.setOnMouseClicked(event -> {
            //判断当前是否在播放
            if (currentPlayBean.getMediaPlayer().getStatus() == MediaPlayer.Status.PLAYING){
                //设置播放器暂停
                currentPlayBean.getMediaPlayer().pause();
                //暂停选择的圆盘
                timeline.pause();
                //设置播放按钮图片为播放
                playBtnImage.setImage(new Image("image/icon/play.png"));
                playLabel.setOnMouseEntered(ee -> playBtnImage.setImage(new Image("image/icon/play-dark.png")));
                playLabel.setOnMouseExited(ee -> playBtnImage.setImage(new Image("image/icon/play.png")));
            }else if (currentPlayBean.getMediaPlayer().getStatus() == MediaPlayer.Status.PAUSED){
                //设置播放器播放
                currentPlayBean.getMediaPlayer().play();
                //启动旋转圆盘
                timeline.play();
                //设置播放按钮图片为播放
                playBtnImage.setImage(new Image("image/icon/pause.png"));
                playLabel.setOnMouseEntered(ee -> playBtnImage.setImage(new Image("image/icon/pause-dark.png")));
                playLabel.setOnMouseExited(ee -> playBtnImage.setImage(new Image("image/icon/pause.png")));
            }
        });
        //下一曲按钮
        ImageView iv3 = new ImageView("image/icon/next.png");
        iv3.setFitHeight(45);
        iv3.setFitWidth(45);
        Label label3 = new Label("",iv3);
        label3.setOnMouseEntered(event -> iv3.setImage(new Image("image/icon/next-dark.png")));
        label3.setOnMouseExited(event -> iv3.setImage(new Image("image/icon/next.png")));
        label3.setOnMouseClicked(event -> {
            if (this.currentPlayBean != null){
                //停止当前播放
                this.currentPlayBean.getMediaPlayer().stop();
                //停止圆盘动画
                this.timeline.stop();
            }
            switch (this.playMode){
                case 1://循环播放
                    this.currentIndex++;//播放下一曲
                    if (this.currentIndex > tableView.getItems().size() - 1){
                        this.currentIndex = 0;//最后一个时，切换到第一首
                    }
                    this.currentPlayBean = tableView.getItems().get(this.currentIndex);
                    break;
                case 2://随机播放
                    Random random = new Random();
                    this.currentIndex = random.nextInt(tableView.getItems().size());//随机获取表格总数内的索引
                    this.currentPlayBean = tableView.getItems().get(this.currentIndex);
                    break;
                case 3://单曲循环
                    this.currentPlayBean.getMediaPlayer().seek(new Duration(0));//设置当前播放时间为0
                    break;
            }
            //播放
            play();
        });
        HBox hBox = new HBox(30);
        hBox.setPrefWidth(320);
        hBox.setPadding(new Insets(5,10,20,10));
        hBox.setAlignment(Pos.CENTER);
        hBox.getChildren().addAll(label1,playLabel,label3);
        //中间滚动条
        //已播放的时间
        playTimeLabel = new Label("00:00");
        playTimeLabel.setPrefWidth(40);
        playTimeLabel.setPrefHeight(30);
        playTimeLabel.setTextFill(Color.WHITE);
        playTimeLabel.setAlignment(Pos.CENTER_LEFT);
        //滚动条
        sliderSong = new Slider();
        sliderSong.setMinHeight(0);
        sliderSong.setMinWidth(0);
        sliderSong.setPrefWidth(300);
        sliderSong.setPrefHeight(12);
        //使用css样式表
        sliderSong.getStylesheets().add("css/TopAndBottomPage.css");
        //进度条
        ProgressBar pb1 = new ProgressBar(0);
        pb1.setMinHeight(0);
        pb1.setMinWidth(0);
        pb1.setMaxWidth(5000);
        pb1.setPrefWidth(300);
        pb1.prefWidthProperty().bind(sliderSong.prefWidthProperty());
        pb1.getStylesheets().add("css/TopAndBottomPage.css");
        //滚动条动带动进度条一起动
        sliderSong.valueProperty().addListener(new ChangeListener<Number>() {
            @Override
            public void changed(ObservableValue<? extends Number> observable, Number oldValue, Number newValue) {
                //设置进度条
                if (currentPlayBean != null){
                    pb1.setProgress((newValue.doubleValue() + 1) / currentPlayBean.getTotalSeconds());
                }
            }
        });
        //slider鼠标抬起事件，设置音乐新的进度和时间
        sliderSong.setOnMouseReleased(event -> {
            if (currentPlayBean != null){
                Duration duration = new Duration(sliderSong.getValue() * 1000);//获取鼠标拖动滚动条的位置（即秒数），乘以1000变成毫秒
                currentPlayBean.getMediaPlayer().seek(duration);//设置新的播放时间
                //同时设置Label
                Date date = new Date();
                date.setTime((long) currentPlayBean.getMediaPlayer().getCurrentTime().toMillis());
                playTimeLabel.setText(new SimpleDateFormat("mm:ss").format(date));
                //设置前一秒
                preSecond = (int)duration.toSeconds() - 1;
            }
        });
        //使用StackPane来存储滚动条和进度条，这样两个就会罗列在一起
        StackPane stackPane = new StackPane();
        stackPane.getChildren().addAll(pb1,sliderSong);
        //总播放时间
        totalTimeLabel = new Label("00:00");
        totalTimeLabel.setPrefWidth(40);
        totalTimeLabel.setPrefHeight(30);
        totalTimeLabel.setTextFill(Color.WHITE);
        totalTimeLabel.setAlignment(Pos.CENTER_RIGHT);
        BorderPane borderPane = new BorderPane();
        borderPane.setLeft(playTimeLabel);
        borderPane.setCenter(stackPane);
        borderPane.setRight(totalTimeLabel);
        borderPane.setPrefHeight(70);
        playTimeLabel.prefHeightProperty().bind(borderPane.prefHeightProperty());
        sliderSong.prefHeightProperty().bind(borderPane.prefHeightProperty());
        totalTimeLabel.prefHeightProperty().bind(borderPane.prefHeightProperty());
        //右侧的一些组件
        //音量图片
        ImageView iv4 = new ImageView("image/icon/laba.png");
        iv4.setFitWidth(25);
        iv4.setFitHeight(25);
        Label label6 = new Label("",iv4);
        label6.setOnMouseEntered(event -> iv4.setImage(new Image("image/icon/laba-dark.png")));
        label6.setOnMouseExited(event -> iv4.setImage(new Image("image/icon/laba.png")));
        label6.setOnMouseClicked(event -> {
            if (currentPlayBean != null){
                if (currentPlayBean.getMediaPlayer().getVolume() != 0){
                    //保存当前音量，用于恢复
                    preVolume = currentPlayBean.getMediaPlayer().getVolume();
                    //设置成静音
                    iv4.setImage(new Image("image/icon/jingyin.png"));
                    label6.setOnMouseEntered(ee -> iv4.setImage(new Image("image/icon/jingyin-dark.png")));
                    label6.setOnMouseExited(ee -> iv4.setImage(new Image("image/icon/jingyin.png")));
                    volumeSlider.setValue(0);
                }else{
                    //恢复之前的音量
                    currentPlayBean.getMediaPlayer().setVolume(preVolume);
                    iv4.setImage(new Image("image/icon/laba.png"));
                    label6.setOnMouseEntered(ee -> iv4.setImage(new Image("image/icon/laba-dark.png")));
                    label6.setOnMouseExited(ee -> iv4.setImage(new Image("image/icon/laba.png")));
                    volumeSlider.setValue(preVolume * 100);
                }
            }
        });
        //音量滚动条
        volumeSlider = new Slider();
        volumeSlider.setMax(100);
        volumeSlider.setValue(50);//默认一般音量
        volumeSlider.setMajorTickUnit(1);//每前进一格，增加多少值
        volumeSlider.setMinHeight(0);
        volumeSlider.setPrefWidth(100);
        volumeSlider.setPrefHeight(10);
        volumeSlider.getStylesheets().add("css/TopAndBottomPage.css");
        //音量进度条
        volumeProgress = new ProgressBar(0);
        volumeProgress.setMinHeight(0);
        volumeProgress.setProgress(0.5);//初始在中间
        volumeProgress.setPrefWidth(100);
        volumeProgress.setMinHeight(10);
        volumeProgress.prefWidthProperty().bind(volumeSlider.prefWidthProperty());
        volumeProgress.getStylesheets().add("css/TopAndBottomPage.css");
        //鼠标释放时修改音量
        volumeSlider.setOnMouseReleased(event -> {
            //设置他的进度条
            volumeProgress.setProgress(volumeSlider.getValue() / 100);
            //设置音量
            if (this.currentPlayBean != null){
                currentPlayBean.getMediaPlayer().setVolume(volumeProgress.getProgress());
            }
        });
        //当音量滚动条滚动时带动进度条
        volumeSlider.valueProperty().addListener(new ChangeListener<Number>() {
            @Override
            public void changed(ObservableValue<? extends Number> observable, Number oldValue, Number newValue) {
                //设置他的进度条
                volumeProgress.setProgress(volumeSlider.getValue() / 100);
                //设置音量
                if (currentPlayBean != null){
                    currentPlayBean.getMediaPlayer().setVolume(volumeProgress.getProgress());
                }
            }
        });
        //把滚动条进度条罗列在一起
        StackPane stackPane1 = new StackPane();
        stackPane1.getChildren().addAll(volumeProgress,volumeSlider);

        //播放模式图片
        ImageView iv5 = new ImageView("image/icon/xunhuan.png");//循环播放
        iv5.setFitWidth(25);
        iv5.setFitHeight(25);
        Label label7 = new Label("",iv5);
        label7.setOnMouseEntered(event -> iv5.setImage(new Image("image/icon/xunhuan-dark.png")));
        label7.setOnMouseExited(event -> iv5.setImage(new Image("image/icon/xunhuan.png")));
        //切换播放模式
        label7.setOnMouseClicked(event -> {
            this.playMode++;
            if (this.playMode > 3){
                this.playMode = 1;
            }
            switch (this.playMode){
                case 1:
                    iv5.setImage(new Image("image/icon/xunhuan.png"));
                    label7.setOnMouseEntered(ee -> iv5.setImage(new Image("image/icon/xunhuan-dark.png")));
                    label7.setOnMouseExited(ee -> iv5.setImage(new Image("image/icon/xunhuan.png")));
                    break;
                case 2:
                    iv5.setImage(new Image("image/icon/suiji.png"));
                    label7.setOnMouseEntered(ee -> iv5.setImage(new Image("image/icon/suiji-dark.png")));
                    label7.setOnMouseExited(ee -> iv5.setImage(new Image("image/icon/suiji.png")));
                    break;
                case 3:
                    iv5.setImage(new Image("image/icon/danqu.png"));
                    label7.setOnMouseEntered(ee -> iv5.setImage(new Image("image/icon/danqu-dark.png")));
                    label7.setOnMouseExited(ee -> iv5.setImage(new Image("image/icon/danqu.png")));
                    break;
            }
        });
        //歌词图片
        ImageView iv6 = new ImageView("image/icon/ci.png");
        iv6.setFitHeight(25);
        iv6.setFitWidth(25);
        Label label8 = new Label("",iv6);
        label8.setOnMouseEntered(event -> iv6.setImage(new Image("image/icon/ci-dark.png")));
        label8.setOnMouseExited(event -> iv6.setImage(new Image("image/icon/ci.png")));
        //拖拽图标
        ImageView iv7 = new ImageView("image/icon/lashen.png");
        iv7.setFitWidth(20);
        iv7.setFitHeight(50);
        Label label9 = new Label("",iv7);
        label9.setPadding(new Insets(10,0,0,10));
        label9.setOnMouseEntered(event -> label9.setCursor(Cursor.NW_RESIZE));
        label9.setOnMousePressed(event -> {
            offsetX = event.getScreenX();
            offsetY = event.getScreenY();
        });
        label9.setOnMouseDragged(event -> {
            //最小窗口宽度为1200
            if (primaryStage.getWidth() + (event.getScreenX() - offsetX) >= 1200){
                primaryStage.setWidth(primaryStage.getWidth() + (event.getScreenX() - offsetX));//设置舞台新的宽度
                offsetX = event.getScreenX();
            }
            //最小窗口高度800
            if (primaryStage.getHeight() + (event.getScreenY() - offsetY) >= 800){
                primaryStage.setHeight(primaryStage.getHeight() + (event.getScreenY() - offsetY));
                offsetY = event.getScreenY();
            }
        });
        HBox hBox1 = new HBox(15);
        hBox1.setPadding(new Insets(0,0,0,10));
        hBox1.setPrefWidth(270);
        hBox1.setAlignment(Pos.CENTER_LEFT);
        hBox1.getChildren().addAll(label6,stackPane1,label7,label8,label9);
        //总的Pane
        BorderPane bottomPane = new BorderPane();
        bottomPane.setLeft(hBox);
        bottomPane.setCenter(borderPane);
        bottomPane.setRight(hBox1);
        return bottomPane;
    }

    /**
     * 获取左侧面板
     * @return
     */
    private Node getLeftPanel() {
        ImageView iv1 = new ImageView("image/upload/banner.png");
        iv1.setFitWidth(300);
        iv1.setPreserveRatio(true);
        Label label1 = new Label("作者：XDY777");
        label1.setPrefWidth(300);
        label1.setTextFill(Color.YELLOW);
        label1.setFont(new Font("黑体",20));
        label1.setAlignment(Pos.CENTER);
        Label label2 = new Label("日期：" + new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
        label2.setPrefWidth(300);
        label2.setTextFill(Color.YELLOW);
        label2.setFont(new Font("黑体",20));
        label2.setAlignment(Pos.CENTER);
        Label label3 = new Label("已创建歌单");
        label3.setPrefWidth(220);
        label3.setTextFill(Color.GRAY);
        label3.setFont(new Font("黑体",16));
        ImageView iv2 = new ImageView("image/icon/add.png");
        iv2.setFitWidth(30);
        iv2.setFitHeight(30);
        Label label4 = new Label("",iv2);
        label4.setMinHeight(0);
        label4.setMinWidth(0);
        label4.setPrefWidth(30);
        label4.setPrefHeight(30);
        label4.setOnMouseEntered(event -> iv2.setImage(new Image("image/icon/add-dark.png")));
        label4.setOnMouseExited(event -> iv2.setImage(new Image("image/icon/add.png")));
        label4.setOnMouseClicked(event -> {
            new AddGroupStage(primaryStage,groupVBox,this);
        });
        HBox hBox = new HBox(30);
        hBox.setPadding(new Insets(10,10,0,10));
        hBox.getChildren().addAll(label3,label4);
        VBox vBox = new VBox(20);//盒子中元素的间距
        vBox.setPrefWidth(300);
        vBox.setPadding(new Insets(0,0,0,30));
        vBox.getChildren().addAll(iv1,label1,label2,hBox);
        //读取所有已创建的歌单
        List<String> groupList = XMLUtils.readAllGroup();
        //将每个歌单封装为一个HBox对象
        List<HBox> hBoxList = new ArrayList<>();
        for (String groupName : groupList) {
            //添加到喜欢图标
            ImageView iv3 = new ImageView("image/icon/favorite.png");
            iv3.setFitWidth(30);
            iv3.setPreserveRatio(true);
            Label label5 = new Label("",iv3);
            label5.setMinWidth(0);
            label5.setMinHeight(0);
            label5.setPrefWidth(30);
            label5.setPrefHeight(30);
            label5.setOnMouseEntered(event -> iv3.setImage(new Image("image/icon/favorite-dark.png")));
            label5.setOnMouseExited(event -> iv3.setImage(new Image("image/icon/favorite.png")));
            //歌单名称
            Label label6 = new Label(groupName);
            label6.setMinWidth(0);
            label6.setPrefHeight(30);
            label6.setPrefWidth(150);
            label6.setTextFill(Color.rgb(210,210,210));
            label6.setOnMouseEntered(event -> label6.setTextFill(Color.rgb(250,250,250)));
            label6.setOnMouseExited(event -> label6.setTextFill(Color.rgb(210,210,210)));
            //播放图片
            ImageView iv4 = new ImageView("image/icon/laba.png");
            iv4.setFitWidth(30);
            iv4.setPreserveRatio(true);
            Label label7 = new Label("",iv4);
            label7.setMinWidth(0);
            label7.setMinHeight(0);
            label7.setPrefWidth(30);
            label7.setPrefHeight(30);
            label7.setOnMouseEntered(event -> iv4.setImage(new Image("image/icon/laba-dark.png")));
            label7.setOnMouseExited(event -> iv4.setImage(new Image("image/icon/laba.png")));
            label7.setOnMouseClicked(event -> {
                //设置当前歌单名称
                this.groupNameLabel.setText(groupName);
                readAllSoundByGroup();
            });
            //添加图标
            ImageView iv5 = new ImageView("image/icon/add.png");
            iv5.setFitWidth(30);
            iv5.setPreserveRatio(true);
            Label label8 = new Label("",iv5);
            label8.setMinWidth(0);
            label8.setMinHeight(0);
            label8.setPrefWidth(30);
            label8.setPrefHeight(30);
            label8.setOnMouseEntered(event -> iv5.setImage(new Image("image/icon/add-dark.png")));
            label8.setOnMouseExited(event -> iv5.setImage(new Image("image/icon/add.png")));
            label8.setOnMouseClicked(event -> {
                //添加歌曲到该歌单
                FileChooser fileChooser = new FileChooser();
                fileChooser.setTitle("选择歌曲");
                File file = fileChooser.showOpenDialog(primaryStage);
                if(file != null && file.getName().substring(file.getName().lastIndexOf(".")).equals(".mp3")){
                    XMLUtils.addSoundWithGroup(groupName,file.getAbsolutePath());
                    //更新歌单列表
                    readAllSoundByGroup();
                    //提示添加成功
                    Alert alert = new Alert(Alert.AlertType.INFORMATION);
                    alert.setTitle("通知");
                    alert.setContentText("添加成功！");
                    alert.show();
                }
            });
            //删除图标
            ImageView iv6 = new ImageView("image/icon/delete.png");
            iv6.setFitWidth(30);
            iv6.setPreserveRatio(true);
            Label label9 = new Label("",iv6);
            label9.setMinWidth(0);
            label9.setMinHeight(0);
            label9.setPrefWidth(30);
            label9.setPrefHeight(30);
            label9.setOnMouseEntered(event -> iv6.setImage(new Image("image/icon/delete-dark.png")));
            label9.setOnMouseExited(event -> iv6.setImage(new Image("image/icon/delete.png")));
            label9.setOnMouseClicked(event -> {
                //删除歌单
                //询问用户确认删除吗
                Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
                alert.setTitle("删除歌单");
                alert.setContentText("确认删除[" + groupName + "]吗？");
                Optional<ButtonType> buttonType = alert.showAndWait();
                if (buttonType.get().equals(ButtonType.OK)){
                    //点击确认，删除歌单
                    XMLUtils.deleteGroup(groupName);
                    //更新歌单VBox
                    this.groupVBox.getChildren().remove(groupHBox);
                }
            });
            //把他们封装到一个HBox中
            groupHBox = new HBox(10);
            groupHBox.setPrefWidth(300);
            groupHBox.getChildren().addAll(label5,label6,label7,label8,label9);
            groupHBox.setPadding(new Insets(5,5,5,20));
            hBoxList.add(groupHBox);
        }
        //把每个HBox遍历添加到VBox中展示
        groupVBox = new VBox();
        groupVBox.setPrefWidth(300);
        groupVBox.setPadding(new Insets(10,10,0,15));
        for (HBox box : hBoxList) {
            groupVBox.getChildren().add(box);
        }
        //总面板
        BorderPane leftPanel = new BorderPane();
        leftPanel.setTop(vBox);
        leftPanel.setCenter(groupVBox);
        return leftPanel;
    }

    /**
     * 读取某个歌单的所有歌曲,封装PlayBean对象
     */
    private void readAllSoundByGroup() {
        //读取此歌单下所有的歌曲
        soundBeans = XMLUtils.getAllSoundWithGroupName(this.groupNameLabel.getText().trim());
        //解析每隔歌曲文件，封装PlayBean
        List<PlayBean> playBeans = new ArrayList<>();
        for (int i = 0; i < soundBeans.size(); i++) {
            SoundBean soundBean = soundBeans.get(i);
            PlayBean playBean = new PlayBean();
            playBean.setId(i + 1);
            //读取音频文件
            File file = new File(soundBean.getFilePath());
            //解析文件
            MP3File mp3File = null;
            try {
                mp3File = new MP3File(file);
            } catch (IOException e) {
                e.printStackTrace();
            } catch (TagException e) {
                e.printStackTrace();
            } catch (ReadOnlyFileException e) {
                e.printStackTrace();
            } catch (InvalidAudioFrameException e) {
                e.printStackTrace();
            }
            //获取MP3文件的头信息
            MP3AudioHeader mp3AudioHeader = (MP3AudioHeader) mp3File.getAudioHeader();
            //获取字符串形式的时长
            String strLength = mp3AudioHeader.getTrackLengthAsString();
            //装换成int的时长
            int intLength = mp3AudioHeader.getTrackLength();
            Set<String> keySet = mp3File.getID3v2Tag().frameMap.keySet();
            String songName = null;//歌名
            String artist = null;//歌手
            String album = null;//专辑名称
            if (keySet.contains("TIT2")){
                ID3v23Frame tit2 = (ID3v23Frame) (mp3File.getID3v2Tag().frameMap.get("TIT2"));
                songName = tit2.getBody().getUserFriendlyValue();
            }
            if(keySet.contains("TPE1")){
                ID3v23Frame tpe1 = (ID3v23Frame) (mp3File.getID3v2Tag().frameMap.get("TPE1"));
                artist = tpe1.getBody().getUserFriendlyValue();
            }
            if(keySet.contains("TALB")){
                ID3v23Frame talb = (ID3v23Frame) (mp3File.getID3v2Tag().frameMap.get("TALB"));
                album = talb.getBody().getUserFriendlyValue();
            }
            //当MP3文件中没有包含音乐标题信息，直接把文件名设置为歌名
            if (songName == null){
                String mp3Name = soundBean.getFilePath().substring(soundBean.getFilePath().lastIndexOf("\\") + 1);
                songName = mp3Name.substring(0, mp3Name.indexOf(".mp3"));
            }
            playBean.setSoundName(songName);
            playBean.setArtist(artist == null ? "" : artist);
            playBean.setAlbum(album == null ? "" : album);
            playBean.setFilePath(soundBean.getFilePath());

            URI uri = file.toURI();
            Media media = new Media(uri.toString());
            MediaPlayer mediaPlayer = new MediaPlayer(media);
            //监听播放器播放
            mediaPlayer.currentTimeProperty().addListener(new ChangeListener<Duration>() {
                @Override
                public void changed(ObservableValue<? extends Duration> observable, Duration oldValue, Duration newValue) {
                    //此方法大概每100毫秒执行一次
                    //获取新的时间的秒
                    int currentSecond = (int) newValue.toSeconds();
                    //设置滚动条，一秒一次
                    if (currentSecond == preSecond + 1){
                        //设置滚动条
                        sliderSong.setValue(sliderSong.getValue() + 1);
                        //设置前一秒
                        preSecond++;
                        //设置新的时间
                        Date date = new Date();
                        date.setTime((int)sliderSong.getValue() * 1000);//当前秒数乘以1000变成毫秒作为参数创建date
                        playTimeLabel.setText(new SimpleDateFormat("mm:ss").format(date));
                    }
                    //设置歌词
                    //获取当前的播放时间
                    double millis = newValue.toMillis();//歌曲播放的总毫秒数
                    //判断此次是否在正常的播放区间
                    double min = 0;//当前行歌词对应总毫秒数
                    double max = 0;//下一行歌词对应总毫秒数
                    if (currentLrcIndex == 0){
                        min = 0;
                    }else{
                        min = lrcList.get(currentLrcIndex).doubleValue();
                    }
                    if (currentLrcIndex != lrcList.size() - 1){
                        //不是最后一个歌词总毫秒数
                        max = lrcList.get(currentLrcIndex + 1).doubleValue();
                    }else{
                        max = lrcList.get(currentLrcIndex).doubleValue();
                    }
                    //判断是否在正常区间内
                    if (millis >= min && millis <= max){
                        return;//歌词显示正确，不需要换行
                    }
                    //如果当前不是最后一行歌词，并且当前播放时长毫秒数大于下一行歌词对应的毫秒数，歌词向上移动一行
                    if (currentLrcIndex < lrcList.size() - 1 &&
                            millis >= lrcList.get(currentLrcIndex + 1).doubleValue()){
                        currentLrcIndex++;//当前歌词索引指示器
                        //上移
                        //时间轴动画
                        Timeline t1 = new Timeline(new KeyFrame(Duration.millis(15),//每隔15毫秒执行一次
                            new EventHandler<ActionEvent>() {
                                @Override
                                public void handle(ActionEvent event) {//动画回调
                                    lrcVBox.setLayoutY(lrcVBox.getLayoutY() - 1);//每15毫秒向上移动1px
                                }
                            }
                        ));
                        t1.setCycleCount(50);//动画执行50次
                        t1.play();
                        //当前歌词变黄
                        Label current_label = (Label) lrcVBox.getChildren().get(currentLrcIndex);
                        current_label.setTextFill(Color.YELLOW);
                        Timeline t2 = new Timeline(new KeyFrame(Duration.millis(30),
                                new EventHandler<ActionEvent>() {
                                    int startFont = 18;
                                    @Override
                                    public void handle(ActionEvent event) {
                                        current_label.setFont(new Font("黑体",startFont++));
                                    }
                                }
                        ));
                        t2.setCycleCount(12);//执行12次
                        t2.play();

                        //前一行变小，变为灰色
                        Label label_pre_1 = (Label) lrcVBox.getChildren().get(currentLrcIndex -1);
                        if (label_pre_1 != null){

                            Timeline t3 = new Timeline(new KeyFrame(Duration.millis(30),
                                    new EventHandler<ActionEvent>() {
                                        int startFont = 30;
                                        @Override
                                        public void handle(ActionEvent event) {
                                            label_pre_1.setFont(new Font("黑体",startFont--));
                                        }
                                    }
                                ));
                            t3.setCycleCount(12);
                            t3.play();
                            t3.setOnFinished(event -> label_pre_1.setTextFill(Color.rgb(114,114,114)));//动画播放完成执行
                        }
                        //前两行
                        if (currentLrcIndex - 2 >= 0){
                            Label label_pre_2 = (Label) lrcVBox.getChildren().get(currentLrcIndex - 2);
                            label_pre_2.setTextFill(Color.rgb(53,53,53));
                        }
                        //如果不是最后一行歌词，后一行设置成白色
                        if (currentLrcIndex + 1 < lrcList.size()){
                            Label next_label = (Label) lrcVBox.getChildren().get(currentLrcIndex + 1);
                            next_label.setTextFill(Color.WHITE);
                        }
                    }else if (currentLrcIndex > 0 && millis < lrcList.get(currentLrcIndex).doubleValue()){
                        //当前歌词索引大于0，并且播放毫秒时间小于当前歌词对应毫秒时间，说明向前拉动了进度条，歌词回退
                        currentLrcIndex--;
                        //下移
                        //时间轴动画
                        Timeline t1 = new Timeline(new KeyFrame(Duration.millis(15),//每隔15毫秒执行一次
                                new EventHandler<ActionEvent>() {
                                    @Override
                                    public void handle(ActionEvent event) {//动画回调
                                        lrcVBox.setLayoutY(lrcVBox.getLayoutY() + 1);//每15毫秒向下移动1px
                                    }
                                }
                        ));
                        t1.setCycleCount(50);//动画执行50次
                        t1.play();
                        //当前歌词变黄
                        Label current_label = (Label) lrcVBox.getChildren().get(currentLrcIndex);
                        current_label.setTextFill(Color.YELLOW);
                        Timeline t2 = new Timeline(new KeyFrame(Duration.millis(30),
                                new EventHandler<ActionEvent>() {
                                    int startFont = 18;
                                    @Override
                                    public void handle(ActionEvent event) {
                                        current_label.setFont(new Font("黑体",startFont++));
                                    }
                                }
                        ));
                        t2.setCycleCount(12);//执行12次
                        t2.play();
                        //下一行歌词变小变白色
                        Label next_label = (Label) lrcVBox.getChildren().get(currentLrcIndex + 1);
                        if (next_label != null){
                            next_label.setTextFill(Color.WHITE);
                            Timeline t3 = new Timeline(new KeyFrame(Duration.millis(30), new EventHandler<ActionEvent>() {
                                int startFont = 30;
                                @Override
                                public void handle(ActionEvent event) {
                                    next_label.setFont(new Font("黑体",startFont--));
                                }
                            }));
                            t3.setCycleCount(12);
                            t3.play();
                        }
                        //下两行设置成灰色
                        Label next_label_2 = (Label) lrcVBox.getChildren().get(currentLrcIndex + 2);
                        if (next_label_2 != null){
                            next_label_2.setTextFill(Color.rgb(114,114,114));
                        }
                        //下三行设置成深灰色
                        Label next_label_3 = (Label) lrcVBox.getChildren().get(currentLrcIndex + 2);
                        if (next_label_3 != null){
                            next_label_3.setTextFill(Color.rgb(53,53,53));
                        }
                    }
                }
            });
            //监听音乐播放完毕
            mediaPlayer.setOnEndOfMedia(() -> {
                if (this.currentPlayBean != null){
                    //停止播放
                    this.currentPlayBean.getMediaPlayer().stop();
                    //停止动画
                    this.timeline.stop();
                    //重新加载歌词
                    this.lrcVBox.setLayoutY(50 * 2 - 10);//重新设置歌词显示第一行
                    this.lrcVBox.getChildren().clear();//清空歌词
                    this.lrcList.clear();//清空歌词毫秒数
                    this.currentLrcIndex = 0;//歌词指示器索引置为起始索引
                }
                switch (this.playMode){
                    case 1://循环播放
                        this.currentIndex++;//播放下一曲
                        if (this.currentIndex > tableView.getItems().size() - 1){
                            this.currentIndex = 0;//最后一个时，切换到第一首
                        }
                        this.currentPlayBean = tableView.getItems().get(this.currentIndex);
                        break;
                    case 2://随机播放
                        Random random = new Random();
                        this.currentIndex = random.nextInt(tableView.getItems().size());//随机获取表格总数内的索引
                        this.currentPlayBean = tableView.getItems().get(this.currentIndex);
                        break;
                    case 3://单曲循环
                        this.currentPlayBean.getMediaPlayer().seek(new Duration(0));//设置当前播放时间为0
                        break;
                }
                //播放
                play();
            });
            playBean.setMediaPlayer(mediaPlayer);

            //计算文件大小
            BigDecimal bigDecimal = new BigDecimal(file.length());//文件大小单位：字节
            BigDecimal result = bigDecimal.divide(new BigDecimal(1024 * 1024), BigDecimal.ROUND_HALF_UP);//换算成MB，四舍五入
            playBean.setLength(result.toString().concat("M"));

            //字符串时间
            playBean.setTime(strLength);
            //总秒数
            playBean.setTotalSeconds(intLength);
            //设置删除图片
            ImageView view = new ImageView("image/icon/delete-gray.png");
            view.setFitWidth(20);
            view.setFitHeight(20);
            Label label = new Label("",view);
            label.setAlignment(Pos.CENTER);
            label.setOnMouseEntered(event -> view.setImage(new Image("image/icon/delete-dark.png")));
            label.setOnMouseExited(event -> view.setImage(new Image("image/icon/delete-gray.png")));
            label.setOnMouseClicked(event -> {
                Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
                alert.setTitle("删除歌曲");
                alert.setContentText("确认删除[" + playBean.getSoundName() +"]吗？");
                Optional<ButtonType> buttonType = alert.showAndWait();
                if (buttonType.get().equals(ButtonType.OK)){
                    //伤处xml下该歌曲对应的group下的sound
                    XMLUtils.deleteSoundWithGroup(groupNameLabel.getText(),soundBean.getFilePath());
                    //更新歌单列表
                    this.tableView.getItems().remove(playBean);
                    //如果删除的是正在播放的歌曲，则停止当前播放，切换到下一首
                    if (playBean == currentPlayBean){
                        currentPlayBean.getMediaPlayer().stop();
                        timeline.stop();
                        switch (playMode){
                            case 1://循环播放
                                this.currentIndex++;//播放下一曲
                                if (this.currentIndex > tableView.getItems().size() - 1){
                                    this.currentIndex = 0;//最后一个时，切换到第一首
                                }
                                this.currentPlayBean = tableView.getItems().get(this.currentIndex);
                                break;
                            case 2://随机播放
                                Random random = new Random();
                                this.currentIndex = random.nextInt(tableView.getItems().size());//随机获取表格总数内的索引
                                this.currentPlayBean = tableView.getItems().get(this.currentIndex);
                                break;
                            case 3://单曲循环
                                this.currentPlayBean.getMediaPlayer().seek(new Duration(0));//设置当前播放时间为0
                                break;
                        }
                        //播放
                        play();
                    }
                }
            });
            playBean.setLabel(label);
            //设置图片
            AbstractID3v2Tag tag = mp3File.getID3v2Tag();
            AbstractID3v2Frame frame = (AbstractID3v2Frame) tag.getFrame("APIC");
            if (frame != null){
                FrameBodyAPIC body = (FrameBodyAPIC) frame.getBody();
                byte[] imageData = body.getImageData();
                //将字节数组转换为Image对象
                java.awt.Image image = Toolkit.getDefaultToolkit().createImage(imageData,0,imageData.length);
                BufferedImage bufferedImage = ImageUtils.toBufferedImage(image);
                WritableImage writableImage = SwingFXUtils.toFXImage(bufferedImage, null);
                playBean.setImage(writableImage);
            }
            //将playBean封装到集合中
            playBeans.add(playBean);
        }
        //将playBeans中的数据显示到表格中
        ObservableList<PlayBean> data = FXCollections.observableList(playBeans);
        this.tableView.getItems().clear();//清空表格
        this.tableView.setItems(data);
    }

    /**
     * 获取顶部面板
     *
     * @return
     */
    private Node getTopPanel() {
        BorderPane topPane = new BorderPane();
        topPane.setPrefHeight(Constants.TOP_PANEL_PRE_HEIGHT);
        topPane.prefWidthProperty().bind(primaryStage.widthProperty());
        //左上角logo
        ImageView iv1 = new ImageView("image/upload/logo.png");
        iv1.setFitHeight(Constants.TOP_PANEL_PRE_HEIGHT);
        iv1.setPreserveRatio(true);
        HBox hBox = new HBox();
        hBox.setAlignment(Pos.CENTER_LEFT);
        hBox.setPrefHeight(Constants.TOP_PANEL_PRE_HEIGHT);
        hBox.setPrefWidth(Constants.TOP_PANEL_LEFT_BOX_WIDTH);
        hBox.setMaxHeight(Constants.TOP_PANEL_PRE_HEIGHT);
        hBox.setPadding(new Insets(10, 0, 10, 0));
        hBox.getChildren().add(iv1);
//        hBox.setBackground(new Background(new BackgroundFill(Color.RED, null, null)));
        //最小化按钮
        ImageView iv2 = new ImageView("image/icon/min.png");
        iv2.setFitHeight(Constants.TOP_PANEL_RIGHT_ICON);
        iv2.setFitWidth(Constants.TOP_PANEL_RIGHT_ICON);
        Label label = new Label("", iv2);
        //取消默认高度宽度
        label.setMinHeight(0);
        label.setMinWidth(0);
        label.setPrefHeight(Constants.TOP_PANEL_RIGHT_ICON);
        label.setPrefWidth(Constants.TOP_PANEL_RIGHT_ICON);
        //鼠标移入
        label.setOnMouseEntered(event -> iv2.setImage(new Image("image/icon/min-dark.png")));
        //鼠标移出
        label.setOnMouseExited(event -> iv2.setImage(new Image("image/icon/min.png")));
        //点击事件
        label.setOnMouseClicked(event -> primaryStage.setIconified(true));//最小化
        HBox hBox2 = new HBox(25);//设置内部元素的间距
        hBox2.setAlignment(Pos.CENTER_LEFT);
        hBox2.setPrefWidth(150);
        hBox2.setPrefHeight(100);
        hBox2.setPadding(new Insets(30,0,0,0));
        //最大化按钮
        ImageView iv3 = new ImageView("image/icon/max.png");
        iv3.setFitHeight(Constants.TOP_PANEL_RIGHT_ICON);
        iv3.setFitWidth(Constants.TOP_PANEL_RIGHT_ICON);
        Label label2 = new Label("", iv3);
        //取消默认高度宽度
        label2.setMinHeight(0);
        label2.setMinWidth(0);
        label2.setPrefHeight(Constants.TOP_PANEL_RIGHT_ICON);
        label2.setPrefWidth(Constants.TOP_PANEL_RIGHT_ICON);
        //鼠标移入
        label2.setOnMouseEntered(event -> iv3.setImage(new Image("image/icon/max-dark.png")));
        //鼠标移出
        label2.setOnMouseExited(event -> iv3.setImage(new Image("image/icon/max.png")));
        //鼠标单机最大化
        label2.setOnMouseClicked(event -> {
            //如果是正常大小，显示最大化
            if (!primaryStage.isMaximized()) {
                iv3.setImage(new Image("image/icon/resize.png"));//设置图标为还原窗口大小
                label2.setOnMouseEntered(ee -> iv3.setImage(new Image("image/icon/resize-dark.png")));
                label2.setOnMouseExited(ee -> iv3.setImage(new Image("image/icon/resize.png")));
                primaryStage.setMaximized(true);
            } else {
                //否则则是最大化窗口，显示还原窗口
                iv3.setImage(new Image("image/icon/max.png"));//设置图标为还原窗口大小
                label2.setOnMouseEntered(ee -> iv3.setImage(new Image("image/icon/max-dark.png")));
                label2.setOnMouseExited(ee -> iv3.setImage(new Image("image/icon/max.png")));
                primaryStage.setMaximized(false);
            }
        });
        //关闭按钮
        ImageView iv4 = new ImageView("image/icon/exit.png");
        iv4.setFitHeight(Constants.TOP_PANEL_RIGHT_ICON);
        iv4.setFitWidth(Constants.TOP_PANEL_RIGHT_ICON);
        Label label3 = new Label("", iv4);
        //取消默认高度宽度
        label3.setMinHeight(0);
        label3.setMinWidth(0);
        label3.setPrefHeight(Constants.TOP_PANEL_RIGHT_ICON);
        label3.setPrefWidth(Constants.TOP_PANEL_RIGHT_ICON);
        //鼠标移入
        label3.setOnMouseEntered(event -> iv4.setImage(new Image("image/icon/exit-dark.png")));
        //鼠标移出
        label3.setOnMouseExited(event -> iv4.setImage(new Image("image/icon/exit.png")));
        //单机退出
        label3.setOnMouseClicked(event -> {
            //保存当前播放歌曲索引和歌单
            XMLUtils.saveLastPlayInfo(this.groupNameLabel.getText(),currentIndex);
            System.exit(0);
        });//直接退出jvm
        //下划线（渐变效果）
        Rectangle rectangle = new Rectangle();
        rectangle.setX(0);
        rectangle.setY(0);
        rectangle.setWidth(100);
        rectangle.setHeight(2);
        //设置渐变色
        Stop[] stops = new Stop[]{
            new Stop(0,Color.rgb(47,47,47)),
            new Stop(0.5,Color.rgb(250,250,250)),
            new Stop(1,Color.rgb(47,47,47))
        };
        rectangle.setFill(new LinearGradient(0,0,1,1,true, CycleMethod.NO_CYCLE,stops));
        rectangle.widthProperty().bind(primaryStage.widthProperty());//将宽度与舞台宽度绑定
        hBox2.getChildren().addAll(label, label2, label3);
        topPane.setRight(hBox2);
        topPane.setLeft(hBox);
        topPane.setBottom(rectangle);
        //处理鼠标拖拽窗口
        topPane.setOnMousePressed(event -> {
            mouseX = event.getSceneX();//获取场景内鼠标的横坐标
            mouseY = event.getSceneY();//获取场景内鼠标的纵坐标
        });
        //当鼠标拖拽时
        topPane.setOnMouseDragged(event -> {
            double primaryStageX = (event.getScreenX() - mouseX);
            double primaryStageY = (event.getScreenY() - mouseY);
            primaryStage.setX(primaryStageX);
            primaryStage.setY(primaryStageY);
        });
        return topPane;
    }

    /**
     * 程序入口
     * @param args
     */
    public static void main(String[] args) {
        launch(args);
    }
}
